package com.atguigu.springsecurity.coutom;

import com.alibaba.fastjson.annotation.JSONField;
import com.atguigu.model.system.SysUser;

import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 自定义用户信息
 */

@Data
@NoArgsConstructor
public class LoginUser implements UserDetails {

    // 登录用户的输入
    private SysUser sysUser;

    //存储权限信息
    private List<String> permissions;

    //存储SpringSecurity所需要的权限信息的集合
    // 这样就不用每次都去查询了
    @JSONField(serialize = false)
    private List<GrantedAuthority> authorities;

    public LoginUser(SysUser user, List<String> permissions) {
        this.sysUser = user;
        this.permissions = permissions;
    }


    /**
     * 获取权限的
     *
     * @return
     */
    @JSONField(serialize = false) // 不被序列化
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        // 创建实现类 SimpleGrantedAuthority 点进去，然后按住ctrl + alt + 左键就可以看见了

        // 这样每次就不用重新生成权限了(集合形式，因为这个人可能有很多的权限信息)
        if (authorities != null && authorities.size() > 0) {
            return authorities;
        }
//        authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        authorities = permissions.stream().map(item -> {
            return new SimpleGrantedAuthority(item);
        }).collect(Collectors.toList());
        return authorities;
    }


    @Override
    public String getPassword() {
        return sysUser.getPassword();
    }

    @Override
    public String getUsername() {
        return sysUser.getUsername();
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
